﻿using Microsoft.AspNetCore.Authorization;
using Wechat_PublicNumber.Entity;

namespace Wechat_PublicNumber.Common
{
    [Injection(DIPattern.Scoped, InitMethod = nameof(Init))]
    public class UserAuthorization : DataAccess
    {
        #region DI
        [Autowired]
        private IJwtHelper _jwtHelper;

        [Autowired]
        private ActionCustomAttributes _actionCustomAttributes;

        [Autowired]
        private IHttpContextAccessor _httpContextAccessor;

        [Autowired]
        private JwtConfig _jwtConfig { get; set; }
        #endregion

        private void Init()
        {
            if (!_actionCustomAttributes.CustomAttributeDatas.Any(s => s.AttributeType == typeof(AllowAnonymousAttribute)))
            {
                var token = _httpContextAccessor.HttpContext.Request.Headers[_jwtConfig.HeaderName].First();

                try
                {
                    var toeknData = _jwtHelper.Decrypt<ToeknData>(token);
                    if (toeknData != null)
                        UserInfo = WXDb.Queryable<UserInfo>().Where(s => s.ID == toeknData.UserID).First();
                }
                catch
                {
                    throw new UnauthorizedException(_jwtConfig.ErrorMessage);
                }
            }
        }

        public UserInfo UserInfo { get; set; }
    }

    public class ToeknData
    {
        public long UserID { get; set; }
    }
}
